package com.unitd.frame.comm.utils.template;

import com.unitd.frame.comm.utils.ExceptionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.util.Map;

/**
 * @desc Velocity工具类, 主要用来在自动代码生成中,根据模板生成相应的代码文件
 * @filename VelocityUtils.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2018/1/19
 */
public class VelocityUtils {

	/**
	 * @desc 读取指定Velocity模板文件,并将指定的数据对象值填充到Velocity模板中,并生成填充后的值
	 * @param templateFilePath Velocity模板文件的路径
	 * @param model 需要填充的数据对象
	 * @return 填充后的实际值串
	 */
	public static String renderString(String templateFilePath, Map<String, ?> model) {
		StringWriter result = new StringWriter();
		try {
			VelocityContext context = new VelocityContext(model);
			Template tpl = Velocity.getTemplate(templateFilePath, "UTF-8");
			tpl.merge(context, result);
			return result.toString();
		} catch (Exception e) {
			throw ExceptionUtils.unchecked(e);
		} finally {
			IOUtils.closeQuietly(result);
		}
	}
}